package com.xc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xc.common.Const;
import com.xc.common.ServerResponse;
import com.xc.dao.*;
import com.xc.pojo.*;
import com.xc.service.*;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.ip.IpUtils;
import com.xc.utils.ip.JuheIpApi;
import com.xc.utils.redis.CookieUtils;
import com.xc.utils.redis.JsonUtil;
import com.xc.utils.redis.RedisShardedPoolUtils;
import com.xc.vo.agent.AgentUserListVO;
import com.xc.vo.position.PositionVO;
import com.xc.vo.position.UserPositionVO;
import com.xc.vo.user.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedTransferQueue;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/15 3:42 PM
 */
@Service("iUserService")
@Slf4j
public class UserServiceImpl implements IUserService{

    @Autowired
    UserMapper userMapper;
    @Autowired
    IAgentUserService iAgentUserService;
    @Autowired
    ISiteLoginLogService iSiteLoginLogService;
    @Autowired
    StockOptionMapper stockOptionMapper;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    IUserPositionService iUserPositionService;
    @Autowired
    IUserBankService iUserBankService;
    @Autowired
    AgentUserMapper agentUserMapper;
    @Autowired
    SiteTaskLogMapper siteTaskLogMapper;
    @Autowired
    IStockOptionService iStockOptionService;
    @Autowired
    ISiteSettingService iSiteSettingService;

    @Override
    public ServerResponse reg(String yzmCode, String agentCode, String phone, String userPwd, HttpServletRequest request) {

        if(StringUtils.isBlank(agentCode) || StringUtils.isBlank(phone) ||
                StringUtils.isBlank(userPwd) || StringUtils.isBlank(yzmCode)
                ){
            return ServerResponse.createByErrorMsg("注册失败，参数不能为空");
        }

        //  判断手机验证码
        String keys = Const.SmsKeyPrefix.ALIYUN_PREFIX + phone;
        String redis_yzm = RedisShardedPoolUtils.get(keys);

        log.info("redis_yzm = {},yzmCode = {}",redis_yzm,yzmCode);
        if(!yzmCode.equals(redis_yzm)){
            return ServerResponse.createByErrorMsg("注册失败，验证码错误");
        }

        //  判断代理是否存在
        AgentUser agentUser = iAgentUserService.findByCode(agentCode);
        if(agentUser == null){
            return ServerResponse.createByErrorMsg("注册失败，代理不存在");
        }
        if(agentUser.getIsLock() == Const.AgentUserLockStatus.lock){
            return ServerResponse.createByErrorMsg("注册失败，代理已被锁定");
        }

        //  判断手机号是否已经注册
        User dbuser = userMapper.findByPhone(phone);
        if(dbuser != null){
            return ServerResponse.createByErrorMsg("注册失败，手机号已注册");
        }

        //  保存用户
        User user = new User();
        user.setAgentId(agentUser.getId());
        user.setAgentName(agentUser.getAgentName());
        user.setPhone(phone);
        user.setUserPwd(userPwd);
//        user.setNickName(nickName);
//        user.setRealName(realName);
        user.setAccountType(Const.UserAccountType.zhengshi);
        user.setIsLock(Const.UserLockStatus.lock);
        user.setIsActive(Const.UserActiveStatus.reg_active);

        user.setRegTime(new Date());
        String uip = IpUtils.getIp(request);
        user.setRegIp(uip);
        String uadd = JuheIpApi.ip2Add(uip);
        user.setRegAddress(uadd);

        user.setIsLogin(0);
        user.setUserAmt(new BigDecimal("0"));
        user.setEnableAmt(new BigDecimal("0"));
        user.setSumBuyAmt(new BigDecimal("0"));
        user.setSumChargeAmt(new BigDecimal("0"));

        int insertCount = userMapper.insert(user);

        if(insertCount > 0){
            log.info("用户注册成功 手机 {} ，ip = {} 地址 = {}",phone,uip,uadd);
            return ServerResponse.createBySuccessMsg("注册成功.请登录");
        }else{
            return ServerResponse.createBySuccessMsg("注册出错，请重试");
        }
    }

    @Override
    public ServerResponse login(String phone, String userPwd, HttpServletRequest request) {
        if(StringUtils.isBlank(phone) || StringUtils.isBlank(userPwd)){
            return ServerResponse.createByErrorMsg("手机号和密码不能为空");
        }

        User user = userMapper.login(phone,userPwd);
        if(user != null){
            if(user.getIsLogin() == Const.UserLoginStatus.lock){
                return ServerResponse.createByErrorMsg("登陆失败，账户被锁定");
            }

            log.info("用户{}登陆成功,登陆状态{},交易状态{}" , user.getId() ,user.getIsLogin(), user.getIsLock());

            iSiteLoginLogService.saveLog(user,request);
            return ServerResponse.createBySuccess(user);
        }else{
            return ServerResponse.createByErrorMsg("登陆失败，用户名密码错误");
        }
    }

    @Override
    public User getCurrentUser(HttpServletRequest request) {
        String loginToken = CookieUtils
                .readLoginToken(request, PropertiesUtil.getProperty("user.cookie.name"));
        String userJson = RedisShardedPoolUtils.get(loginToken);
        return JsonUtil.string2Obj(userJson,User.class);
    }
    @Override
    public User getCurrentRefreshUser(HttpServletRequest request) {
        String loginToken = CookieUtils
                .readLoginToken(request,PropertiesUtil.getProperty("user.cookie.name"));
        String userJson = RedisShardedPoolUtils.get(loginToken);
        User user = JsonUtil.string2Obj(userJson,User.class);
        User dbuser = userMapper.selectByPrimaryKey(user.getId());
        return dbuser;
    }

    @Override
    public synchronized ServerResponse addOption(String code , HttpServletRequest request) {

        User user = getCurrentUser(request);

        //  查找是否已经存在
        StockOption dboption = stockOptionMapper
                .findMyOptionIsExistByCode(user.getId(),code);

        if(dboption != null){
            return ServerResponse.createByErrorMsg("添加失败，自选股已存在");
        }

        //  查询股票表
        Stock stock = stockMapper.findStockByCode(code);
        if(stock == null){
            return ServerResponse.createByErrorMsg("添加失败，股票不存在");
        }

        //  保存自选股
        StockOption stockOption = new StockOption();
        stockOption.setUserId(user.getId());
        stockOption.setStockId(stock.getId());
        stockOption.setAddTime(new Date());

        stockOption.setStockCode(stock.getStockCode());
        stockOption.setStockName(stock.getStockName());
        stockOption.setStockGid(stock.getStockGid());
        stockOption.setIsLock(stock.getIsLock());

        int insertCount = stockOptionMapper.insert(stockOption);
        if(insertCount > 0){
            return ServerResponse.createBySuccessMsg("添加自选股成功");
        }else{
            return ServerResponse.createByErrorMsg("添加失败，请重试");
        }

    }

    @Override
    public ServerResponse delOption(String code, HttpServletRequest request) {
        User user = getCurrentUser(request);

        //  查找是否已经存在
        StockOption dboption = stockOptionMapper
                .findMyOptionIsExistByCode(user.getId(),code);

        if(dboption == null){
            return ServerResponse.createByErrorMsg("删除失败，自选股不存在");
        }

        int delCount = stockOptionMapper.deleteByPrimaryKey(dboption.getId());
        if(delCount > 0){
            return ServerResponse.createBySuccessMsg("删除自选股成功");
        }else{
            return ServerResponse.createByErrorMsg("删除失败，请重试");
        }
    }

    @Override
    public ServerResponse isOption(String code, HttpServletRequest request) {
        User user = getCurrentUser(request);
        return iStockOptionService.isOption(user.getId(),code);
    }

    @Override
    public ServerResponse getUserInfo(HttpServletRequest request) {

        String loginToken = CookieUtils
                .readLoginToken(request,PropertiesUtil.getProperty("user.cookie.name"));
        String userJson = RedisShardedPoolUtils.get(loginToken);
        User user = JsonUtil.string2Obj(userJson,User.class);
        User dbuser = userMapper.selectByPrimaryKey(user.getId());

        UserInfoVO userInfoVO = assembleUserInfoVO(dbuser);

        return ServerResponse.createBySuccess(userInfoVO);
    }

    @Override
    public ServerResponse updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        if(StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        User user = getCurrentUser(request);
        if(!oldPwd.equals(user.getUserPwd())){
            return ServerResponse.createByErrorMsg("密码错误");
        }

        user.setUserPwd(newPwd);
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }

    @Override
    public ServerResponse checkPhone(String phone) {
        User user = userMapper.findByPhone(phone);
        if(user != null){
            return ServerResponse.createBySuccessMsg("用户已存在");
        }else{
            return ServerResponse.createByErrorMsg("用户不存在");
        }
    }

    @Override
    public ServerResponse updatePwd(String phone, String code, String newPwd) {
        if(StringUtils.isBlank(phone)
                || StringUtils.isBlank(code)
                || StringUtils.isBlank(newPwd)){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        //  判断手机验证码
        String keys = Const.SmsKeyPrefix.ALIYUN_PREFIX + phone;
        String redis_yzm = RedisShardedPoolUtils.get(keys);

        log.info("redis_yzm = {} , code = {}" , redis_yzm , code);
        if(!code.equals(redis_yzm)){
            return ServerResponse.createByErrorMsg("修改密码失败，验证码错误");
        }

        User user = userMapper.findByPhone(phone);
        if(user == null){
            return ServerResponse.createByErrorMsg("用户不存在");
        }

        user.setUserPwd(newPwd);
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("修改密码成功！");
        }else{
            return ServerResponse.createByErrorMsg("修改密码失败！");
        }
    }

    @Override
    public ServerResponse update(User user) {
        if(user.getAgentId() != null){
            AgentUser agentUser = agentUserMapper.selectByPrimaryKey(user.getAgentId());
            if(agentUser != null){
                user.setAgentName(agentUser.getAgentName());
            }
        }

        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }

    @Override
    public ServerResponse auth(String realName, String idCard
            ,String img1key,String img2key,String img3key
            , HttpServletRequest request) {

        if(StringUtils.isBlank(realName)
                || StringUtils.isBlank(idCard)
                || StringUtils.isBlank(img1key)
                || StringUtils.isBlank(img2key)
//                || StringUtils.isBlank(img3key)
                ){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        User user = getCurrentRefreshUser(request);
        if(user == null){
            return ServerResponse.createByErrorMsg("请先登录！");
        }

        if(Const.UserActiveStatus.reg_active != user.getIsActive()
                & Const.UserActiveStatus.fail_active != user.getIsActive()
                ){
            return ServerResponse.createByErrorMsg("当前状态不能认证");
        }

        user.setNickName(realName);
        user.setRealName(realName);
        user.setIdCard(idCard);

        user.setImg1Key(img1key);
        user.setImg2Key(img2key);
        user.setImg3Key(img3key);
        user.setIsActive(Const.UserActiveStatus.auth_active);

        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("实名认证中");
        }else{
            return ServerResponse.createByErrorMsg("实名认证失败");
        }
    }

    @Override
    public void ForceSellTask() {
        //  首先查询当前有持仓单的用户id
        List<Integer> userIdList = iUserPositionService.findDistinctUserIdList();

        log.info("当前有持仓单的用户数量 为 {}" , userIdList.size());

        for (int i = 0; i < userIdList.size(); i++){
            log.info("=====================");
            Integer userId = userIdList.get(i);
            User user = userMapper.selectByPrimaryKey(userId);

            List<UserPosition> userPositions = iUserPositionService
                    .findPositionByUserIdAndSellIdIsNull(userId);

            log.info("用户id = {} 姓名 = {} 持仓中订单数： {}" , userId,user.getRealName(),userPositions.size());

            //  计算用户是否达到强制平仓线
            BigDecimal enable_user_amt = user.getEnableAmt();

            //  全部的冻结保证金
            BigDecimal all_freez_amt = new BigDecimal("0");
            for (UserPosition position : userPositions){

                BigDecimal actual_amt = position.getOrderTotalPrice().divide(
                        new BigDecimal(position.getOrderLever()),2,BigDecimal.ROUND_HALF_UP);
//                log.info("持仓单{} 总市值 {} 杠杆倍数 {} 实际支付保证金 {} "
//                        ,position.getId(),position.getOrderTotalPrice(),position.getOrderLever(),actual_amt);

                all_freez_amt = all_freez_amt.add(actual_amt);
            }

            //  当前所有持仓单的盈亏
            BigDecimal all_profit_and_lose = new BigDecimal("0");
            PositionVO positionVO = iUserPositionService.findUserPositionAllProfitAndLose(userId);
            all_profit_and_lose = positionVO.getAllProfitAndLose();

//            log.info("用户可用资金 = {} 总冻结保证金 = {} 所有持仓单的总盈亏 = {}"
//                    , enable_user_amt,all_freez_amt,all_profit_and_lose);

            //  开始计算是否达到强平线
            SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
            BigDecimal force_stop_percent = siteSetting.getForceStopPercent();
            BigDecimal force_stop_amt = force_stop_percent.multiply(all_freez_amt);

            //  用户强制平仓线 = 用户可用资金 + 冻结保证金 *0.7
            BigDecimal user_force_amt = enable_user_amt.add(force_stop_amt);
//            log.info("用户强制平仓线金额 = {}" , user_force_amt);

            boolean isProfit = false;
            isProfit = all_profit_and_lose.compareTo(new BigDecimal("0"))== -1
                    && user_force_amt.compareTo(all_profit_and_lose.negate()) != 1;

            if(isProfit){
                log.info("强制平仓该用户所有的持仓单");
                //  强制平仓这个用户所有的持仓单
                int[] arrs = new int[userPositions.size()];
                for (int k = 0; k < userPositions.size(); k++){
                    UserPosition position = userPositions.get(k);
                    arrs[k] = position.getId();
                    try {
                        iUserPositionService.sell(position.getPositionSn(), Const.SellStockDoType.admin_do_type);
                    }catch (Exception e){
                        log.error("【盈亏达到最大亏损】强制平仓失败...");
                    }
                }

                //  保存task记录
                SiteTaskLog siteTaskLog = new SiteTaskLog();
                siteTaskLog.setTaskType(Const.SiteTaskType.forceStockSell_profitAndLose_TASK);
                String accountType = user.getAccountType() == 0 ? "正式用户" : "模拟用户";
                String taskcnt = accountType + user.getRealName()+"被强平【盈亏达到最大亏损】用户id = " + user.getId()
                        + ",可用资金 = "+ enable_user_amt + "冻结保证金 = " + all_freez_amt
                        +",总盈亏：" + all_profit_and_lose + ",强平线:" + user_force_amt
                        ;
                siteTaskLog.setTaskCnt(taskcnt);
                String tasktarget = "此次强平" + userPositions.size() + "条持仓订单，" + "订单号为" + Arrays.toString(arrs);
                siteTaskLog.setTaskTarget(tasktarget);
                siteTaskLog.setAddTime(new Date());
                siteTaskLog.setIsSuccess(0);
                siteTaskLog.setErrorMsg("");
                int insertTaskCount = siteTaskLogMapper.insert(siteTaskLog);
                if(insertTaskCount > 0){
                    log.info("【盈亏达到最大亏损】保存强制平仓task任务成功");
                }else{
                    log.info("【盈亏达到最大亏损】保存强制平仓task任务失败");
                }
            }else{
                log.info("用户未达到强制平仓线，不做强平处理...");
            }

            log.info("=====================");
        }


    }


    @Override
    public ServerResponse listByAgent(String realName, String phone, Integer agentId
            , Integer accountType, int pageNum, int pageSize, HttpServletRequest request) {
        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();

        //  当前登陆代理
        AgentUser currentAgent = iAgentUserService.getCurrentAgent(request);
        //  如果传入了agentId,首先判断agentId是否为当前代理下
        if(agentId != null){
            AgentUser agentUser = agentUserMapper.selectByPrimaryKey(agentId);
            if(agentUser.getParentId() != currentAgent.getId()){
                return ServerResponse.createByErrorMsg("不能查询非下级代理用户持仓");
            }
        }
        Integer searchId = null;
        if(agentId == null){
            searchId = currentAgent.getId();    //  如果传入id为空，查询登陆代理的用户
        }else{
            searchId = agentId;
        }

        PageHelper.startPage(pageNum,pageSize);

        List<User> users = userMapper.listByAgent(realName,phone,searchId,accountType);

        List<AgentUserListVO> agentUserListVOS = Lists.newArrayList();
        for (User user : users){
            AgentUserListVO agentUserListVO = assembleAgentUserListVO(user,siteSetting.getForceStopPercent());
            agentUserListVOS.add(agentUserListVO);
        }

        PageInfo pageInfo = new PageInfo(users);
        pageInfo.setList(agentUserListVOS);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse addSimulatedAccount(Integer agentId,String phone, String pwd,String amt, HttpServletRequest request) {
        if(StringUtils.isBlank(phone) || StringUtils.isBlank(pwd)){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        //  判断手机号是否注册
        User dbUser = userMapper.findByPhone(phone);
        if(dbUser != null){
            return ServerResponse.createByErrorMsg("手机号已注册");
        }

        //  判断总资金
        if(new BigDecimal(amt).compareTo(new BigDecimal("200000")) == 1){
            return ServerResponse.createByErrorMsg("模拟账户资金不能超过20万");
        }

        //  添加用户
        User user = new User();
        user.setAccountType(Const.UserAccountType.moni);
        user.setPhone(phone);
        user.setUserPwd(pwd);
        user.setUserAmt(new BigDecimal(amt));
        user.setEnableAmt(new BigDecimal(amt));
        user.setIsLock(Const.UserLockStatus.zhengchang);
        user.setIsActive(Const.UserActiveStatus.reg_active);
        user.setRegTime(new Date());
        user.setNickName("模拟用户");

        if(agentId != null){
            AgentUser agentUser = agentUserMapper.selectByPrimaryKey(agentId);
            user.setAgentName(agentUser.getAgentName());
            user.setAgentId(agentUser.getId());
        }

        int insertCount = userMapper.insert(user);
        if(insertCount > 0){
            return ServerResponse.createBySuccessMsg("添加用户成功");
        }else{
            return ServerResponse.createByErrorMsg("添加用户失败");
        }

    }

    @Override
    public ServerResponse listByAdmin(String realName, String phone, Integer agentId, Integer accountType, int pageNum, int pageSize, HttpServletRequest request) {

        PageHelper.startPage(pageNum,pageSize);

        List<User> users = userMapper.listByAdmin(realName,phone,agentId,accountType);

        PageInfo pageInfo = new PageInfo(users);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse findByUserId(Integer userId) {
        return ServerResponse.createBySuccess(userMapper.selectByPrimaryKey(userId));
    }

    @Override
    public ServerResponse updateLock(Integer userId) {

        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMsg("用户不存在");
        }

        if(user.getIsLock() == Const.UserLockStatus.lock){
            user.setIsLock(Const.UserLockStatus.zhengchang);
        }else{
            user.setIsLock(Const.UserLockStatus.lock);
        }

        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }

    @Override
    @Transactional
    public ServerResponse updateAmt(Integer userId, Integer amt, Integer direction) {
        if(userId == null || amt == null || direction == null){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMsg("用户不存在");
        }

        BigDecimal user_amt = user.getUserAmt();
        BigDecimal user_enable = user.getEnableAmt();

        BigDecimal user_amt_back = new BigDecimal("0");
        BigDecimal user_enable_back = new BigDecimal("0");
        if(direction == Const.AdminAddMoneyDirection.add){
            user_amt_back = user_amt.add(new BigDecimal(amt));
            user_enable_back = user_enable.add(new BigDecimal(amt));
        }else if(direction == Const.AdminAddMoneyDirection.substract){

            if(user_amt.compareTo(new BigDecimal(amt)) == -1 ){
                return ServerResponse.createByErrorMsg("扣款失败，总资金不足");
            }
            if(user_enable.compareTo(new BigDecimal(amt)) == -1){
                return ServerResponse.createByErrorMsg("扣款失败，可用资金不足");
            }

            user_amt_back = user_amt.subtract(new BigDecimal(amt));
            user_enable_back = user_enable.subtract(new BigDecimal(amt));
        }else{
            return ServerResponse.createByErrorMsg("不存在此操作类型");
        }

        //  修改用户资金
        user.setUserAmt(user_amt_back);
        user.setEnableAmt(user_enable_back);
        userMapper.updateByPrimaryKeySelective(user);

        //  保存task日志
        SiteTaskLog siteTaskLog = new SiteTaskLog();
        siteTaskLog.setTaskType(Const.SiteTaskType.adminUpdateMoney);
        StringBuffer cnt = new StringBuffer();
        cnt.append("管理员修改金额 - ")
                .append(direction == Const.AdminAddMoneyDirection.add ? "入款" : "扣款")
                .append(amt).append("元");
        siteTaskLog.setTaskCnt(cnt.toString());

        StringBuffer target = new StringBuffer();
        target.append("用户id : ").append(user.getId())
                .append("修改前 总资金 = ").append(user_amt).append(" 可用 = ").append(user_enable)
                .append("，修改后 总资金 = ").append(user_amt_back).append(" 可用 = ").append(user_enable_back);
        siteTaskLog.setTaskTarget(target.toString());

        siteTaskLog.setIsSuccess(Const.SiteTaskStatus.success);
        siteTaskLog.setAddTime(new Date());

        int insertCount = siteTaskLogMapper.insert(siteTaskLog);
        if(insertCount > 0){
            return ServerResponse.createBySuccessMsg("修改资金成功");
        }else{
            return ServerResponse.createByErrorMsg("修改资金失败");
        }

    }

    @Override
    public int CountUserSize(Integer accountType) {
        int Count = userMapper.CountUserSize(accountType);
        return Count;
    }

    @Override
    public BigDecimal CountUserAmt(Integer accountType) {
        return userMapper.CountUserAmt(accountType);
    }

    @Override
    public BigDecimal CountEnableAmt(Integer accountType) {
        return userMapper.CountEnableAmt(accountType);
    }

    @Override
    public ServerResponse authByAdmin(Integer userId,Integer state, String authMsg) {

        if(state == null || userId == null){
            return ServerResponse.createByErrorMsg("id和state不能为空");
        }

        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMsg("查不到此用户");
        }

        if(state == Const.UserActiveStatus.fail_active){
            if(StringUtils.isBlank(authMsg)){
                return ServerResponse.createByErrorMsg("审核失败信息必填");
            }else{
                user.setAuthMsg(authMsg);
            }
        }
        user.setIsActive(state);

        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("审核成功");
        }else{
            return ServerResponse.createByErrorMsg("审核失败");
        }
    }


    private AgentUserListVO assembleAgentUserListVO(User user,BigDecimal forcePercent){
        AgentUserListVO agentUserListVO = new AgentUserListVO();

        agentUserListVO.setId(user.getId());
        agentUserListVO.setAgentId(user.getAgentId());
        agentUserListVO.setAgentName(user.getAgentName());
        agentUserListVO.setPhone(user.getPhone());
        agentUserListVO.setRealName(user.getRealName());
        agentUserListVO.setIdCard(user.getIdCard());
        agentUserListVO.setAccountType(user.getAccountType());
        agentUserListVO.setUserAmt(user.getUserAmt());
        agentUserListVO.setEnableAmt(user.getEnableAmt());
        agentUserListVO.setIsLock(user.getIsLock());
        agentUserListVO.setIsLogin(user.getIsLogin());
        agentUserListVO.setRegAddress(user.getRegAddress());
        agentUserListVO.setIsActive(user.getIsActive());

        //  设置当前盈亏
        PositionVO positionVO = iUserPositionService.findUserPositionAllProfitAndLose(user.getId());
        BigDecimal allProfitAndLose = positionVO.getAllProfitAndLose();
        BigDecimal allFreezAmt = positionVO.getAllFreezAmt();
        agentUserListVO.setAllProfitAndLose(allProfitAndLose);
        agentUserListVO.setAllFreezAmt(allFreezAmt);

        //  首先计算强制平仓线 forceLine
        BigDecimal forceLine = forcePercent.multiply(allFreezAmt);
        forceLine = forceLine.add(user.getEnableAmt());

        agentUserListVO.setForceLine(forceLine);


        //  查询用户银行卡信息
        UserBank userBank = iUserBankService.findUserBankByUserId(user.getId());
        if(userBank != null){
            agentUserListVO.setBankName(userBank.getBankName());
            agentUserListVO.setBankNo(userBank.getBankNo());
            agentUserListVO.setBankAddress(userBank.getBankAddress());
        }

        return agentUserListVO;
    }
    private UserInfoVO assembleUserInfoVO(User user){
        UserInfoVO userInfoVO = new UserInfoVO();

        userInfoVO.setId(user.getId());
        userInfoVO.setAgentId(user.getAgentId());
        userInfoVO.setAgentName(user.getAgentName());
        userInfoVO.setPhone(user.getPhone());
        userInfoVO.setNickName(user.getNickName());
        userInfoVO.setRealName(user.getRealName());
        userInfoVO.setIdCard(user.getIdCard());
        userInfoVO.setAccountType(user.getAccountType());
        userInfoVO.setEnableAmt(user.getEnableAmt());
        userInfoVO.setRecomPhone(user.getRecomPhone());
        userInfoVO.setIsLock(user.getIsLock());
        userInfoVO.setRegTime(user.getRegTime());
        userInfoVO.setRegIp(user.getRegIp());
        userInfoVO.setRegAddress(user.getRegAddress());
        userInfoVO.setImg1Key(user.getImg1Key());
        userInfoVO.setImg2Key(user.getImg2Key());
        userInfoVO.setImg3Key(user.getImg3Key());
        userInfoVO.setIsActive(user.getIsActive());
        userInfoVO.setAuthMsg(user.getAuthMsg());

        PositionVO positionVO = iUserPositionService
                .findUserPositionAllProfitAndLose(user.getId());

        //  用户所有的冻结保证金
        userInfoVO.setAllFreezAmt(positionVO.getAllFreezAmt());

        //  用户所有持仓单总盈亏
        BigDecimal allProfitAndLose = positionVO.getAllProfitAndLose();
        userInfoVO.setAllProfitAndLose(allProfitAndLose);

        //  用户的总资金应该加上浮动盈亏
        BigDecimal userAllAmt = user.getUserAmt();

        userAllAmt = userAllAmt.add(allProfitAndLose);
        userInfoVO.setUserAmt(userAllAmt);

        return userInfoVO;
    }


    public static void main(String[] args) {
        int a = 3;

        System.out.println(a!=0);
        System.out.println(a!=3);

        System.out.println(a != 0 & a != 3);
        System.out.println(a != 0 && a != 3);


        if(a != 0 && a != 3){
            System.out.println("不能认证");
        }else{
            System.out.println("可以认证");
        }


    }

}
